﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class MyHttpLoginBase
    {
        string cookiesForUser = "";
        CookieContainer _cookies = new CookieContainer();
        string _lasturl = null;
        string _useragent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; FunWebProducts; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.1)";
        //int _retries = 3;

        #region Properties
        public string UserAgent
        {
            get { return _useragent; }
            set { _useragent = value; }
        }

        public CookieContainer Cookies
        {
            get { return _cookies; }
            set { _cookies = value; }
        }

        public string CookiesForUser
        {
            get { return cookiesForUser; }
            set { cookiesForUser = value; }
        }

        public string LastUrl
        {
            get { return _lasturl; }
            set { _lasturl = value; }
        }

        public void ClearCookies()
        {
            _cookies = new CookieContainer();
        }
        #endregion

        #region Constructors_Destructors
        public MyHttpLoginBase()
        {
            //* Stops gay errors on post. *//
            System.Net.ServicePointManager.UseNagleAlgorithm = false;
            System.Net.ServicePointManager.Expect100Continue = false;
        }
        #endregion

        #region My Post_Get_Functions
        public bool SetCookiesForUser(string url, string postdata)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            if (_lasturl != null)
            {
                req.Referer = _lasturl;
            }
            else
            {
                req.Referer = url;
            }
            _lasturl = url;
            req.Method = "POST";
            req.UserAgent = _useragent;
            req.CookieContainer = _cookies;
            req.ContentLength = postdata.Length;
            using (Stream stream = req.GetRequestStream())
            using (StreamWriter sw = new StreamWriter(stream))
            {
                sw.Write(postdata);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            this.cookiesForUser = String.IsNullOrEmpty(resp.Headers["Set-Cookie"]) ? "" : resp.Headers["Set-Cookie"];

            MessageBox.Show("SetCookiesForUser: \n" + cookiesForUser);


            return !String.IsNullOrEmpty(this.cookiesForUser);
        }

        public string GetContentForCurrentUser(string url, ListBox lb)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.ContentType = "application/x-www-form-urlencoded";
                if (_lasturl != null)
                {
                    req.Referer = _lasturl;
                }
                else
                {
                    req.Referer = url;
                }

                _lasturl = url;
                req.UserAgent = _useragent;
                req.CookieContainer = _cookies;
                req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                req.Headers.Add("Accept-Language", "ru");
                req.ContentType = "application/x-www-form-urlencoded";

                req.Headers.Add(HttpRequestHeader.Cookie, this.cookiesForUser);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                //this.cookiesForUser = String.IsNullOrEmpty(resp.Headers["Set-Cookie"]) ? "" : resp.Headers["Set-Cookie"];

                using (Stream stream = resp.GetResponseStream())
                using (StreamReader sr = new StreamReader(stream, Encoding.Default))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            throw new Exception("Failed");
        }

        public Stream GetContentInXml(string url)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.ContentType = "application/x-www-form-urlencoded";
                if (_lasturl != null)
                {
                    req.Referer = _lasturl;
                }
                else
                {
                    req.Referer = url;
                }

                _lasturl = url;
                req.UserAgent = _useragent;
                req.CookieContainer = _cookies;
                req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                req.Headers.Add("Accept-Language", "ru");
                req.ContentType = "application/x-www-form-urlencoded";

                req.Headers.Add(HttpRequestHeader.Cookie, this.cookiesForUser);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                //this.cookiesForUser = String.IsNullOrEmpty(resp.Headers["Set-Cookie"]) ? "" : resp.Headers["Set-Cookie"];

                using (Stream stream = resp.GetResponseStream())
                {
                    return stream;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            throw new Exception("Failed");
        }

        public string Post(string url, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            if (_lasturl != null)
            {
                req.Referer = _lasturl;
            }
            else
            {
                req.Referer = url;
            }
            _lasturl = url;
            req.Method = "POST";
            req.UserAgent = _useragent;
            req.CookieContainer = _cookies;
            req.ContentLength = postdata.Length;
            using (Stream stream = req.GetRequestStream())
            using (StreamWriter sw = new StreamWriter(stream))
            {
                sw.Write(postdata);
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            //this.cookiesForUser = String.IsNullOrEmpty(resp.Headers["Set-Cookie"]) ? "" : resp.Headers["Set-Cookie"];
            //MessageBox.Show("Post: \n" + cookiesForUser);

            using (Stream stream = resp.GetResponseStream())
            using (StreamReader sr = new StreamReader(stream))
            {
                return sr.ReadToEnd();
            }
        }

        public static string Encode(string str)
        {
            return System.Web.HttpUtility.UrlEncode(str, Encoding.GetEncoding(1251));
        }
        #endregion
    }
}
